<template>
	<view>
		<button class="phone-button" plain="true" size="mini" open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">获取手机号</button>
		<u-toast ref="uToast"/>
	</view>
</template>

<script>
	import {getPhoneNumber,bindPhone} from '@/apis/public/index.js' 
	export default{
		methods:{
			async handleGetPhoneNumber({detail}){
				const {iv,encryptedData,errMsg} = detail
				if(iv && encryptedData && errMsg === 'getPhoneNumber:ok'){
					const [,res] = await uni.login()
					if(res.errMsg==='login:ok'){
						const {code,data,info} = await getPhoneNumber({
							iv,
							encryptedData:encodeURIComponent(encryptedData), // 防止传输转码，字符 "+" 变空格 
							code:res.code
						})
						if(code === 1){
							
							const {code,msg,time} = await bindPhone({
								uid:uni.getStorageSync('userId'),
								phone:data.phoneNumber,
								openid:uni.getStorageSync('openId')
							})
							this.$emit('change',data.phoneNumber)
							this.$refs.uToast.show({title: '手机号获取成功！',type: 'success',position:'top'})
						}else{
							this.$refs.uToast.show({title: info,type: 'error',position:'top'})
						}
					}else{
						this.$refs.uToast.show({title: res.errMsg,type: 'error',position:'top'})
					}
				}else{
					this.$refs.uToast.show({title: errMsg,type: 'error',position:'top'})
				}
			}
		}
	}
</script>

<style>
	.phone-button{
		color: #ff9a3b !important;
		border: 1px solid #ff9a3b !important;
		background-color: #FFFFFF !important;
		font-size: 20rpx !important;
		line-height: 1em !important;
		height: 50rpx !important;
		display: inline-flex !important;
		align-items: center !important;
		margin: 0 !important;
		padding: 0 20rpx !important;
	}
</style>
